package lion.web.interceptors.rewrite;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author lion
 * @mail hl_0074@sina.com
 * @date 2011-10-12
 */
public class RewriteRule {

	private String from;
	private String to;
	Pattern patternFrom;
	private boolean last;


	public RewriteRule(String from, String to, boolean last) {

		this.from = from;
		this.to = to;
		this.last = last;

		patternFrom = Pattern.compile(from);
	}

	public String rewrite(String url) {

		Matcher m = patternFrom.matcher(url);

		if (m.find()) {
			try {
				return m.replaceAll(to);
			} catch (Exception e) {
				throw new IllegalArgumentException("illegal rewrite rules from " + this.from + " to " + this.to + " " + e.getMessage());
			}
		}
		return null;
	}

	public boolean isLast() {

		return last;
	}

	public String getFrom() {

		return from;
	}

	public String getTo() {

		return to;
	}

}
